package org.dromara.iot.config;

import org.dromara.iot.domain.MqttConfigurationProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @ClassName Mq
 * @Description: 类描述
 * @Author: 罗老师
 * @CreateDate: 2025/6/15 23:36
 */
@Configuration
@EnableConfigurationProperties(MqttConfigurationProperties.class)
public class MqttOutboundConfiguration {
    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;
    @Bean
    public MessageChannel mqttOutboundChannel(){
        return new DirectChannel();
    }
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutboundMessageHandler(){
        MqttPahoMessageHandler msgHandler = new MqttPahoMessageHandler(
                mqttConfigurationProperties.getUrl(),
                mqttConfigurationProperties.getPubClientId(),mqttPahoClientFactory);
        msgHandler.setDefaultQos(0);
        msgHandler.setDefaultTopic("default");
        msgHandler.setAsync(true);
        return msgHandler;
    }
}
